//
//  LyricUtil.swift
//  歌词工具类
//
//  Created by smile on 2019/4/21.
//  Copyright © 2019 ixuea. All rights reserved.
//

import Foundation

class LyricUtil {
    
    /// 计算当前播放时间是哪一行歌词
    ///
    /// - Parameters:
    ///   - lyric: 歌词对象
    ///   - time: 播放进度；单位秒
    /// - Returns: 找到的位置
    static func getLineNumber(_ lyric:Lyric,_ time:Float) -> Int {
        //将播放进度单位转为毫秒
        //因为歌词中开始时间
        //结束时间都是毫秒
        let newTime=time*1000
        
        for (index,value) in lyric.datas.enumerated().reversed() {
            //倒序遍历每一行歌词
            if newTime>=Float(value.startTime){
                //如果当前的时间
                //正好大于这一行开始时间
                //那么就是当前索引
                return index
            }
          
        }
        
        //如果没找到
        //就是第0行
        return 0
    }
    
    /// 获取当前时间是该行歌词第几个字
    ///
    /// - Parameters:
    ///   - line: <#line description#>
    ///   - time: <#time description#>
    /// - Returns: <#return value description#>
    static func getWordIndex(_ line:LyricLine,_ time:Float) -> Int {
        //转为毫秒
        let newTime=time*1000
        
        var startTime = Float(line.startTime)
        
        for (index,value) in line.wordDurations!.enumerated() {
            startTime=startTime+Float(value)
            if newTime<startTime{
                print("LyricUtil getWordIndex:\(line.data!),\(startTime),\(newTime),\(index)")
                return index
            }
        }
        
        print("LyricUtil getWordIndex:\(line.data!),\(startTime),\(newTime),\(-1)")
        
        return -1
    }
    
    /// 获取当前字已经唱过时间
    ///
    /// - Parameters:
    ///   - line: <#line description#>
    ///   - time: <#time description#>
    /// - Returns: <#return value description#>
    static func getWordPlayedTime(_ line:LyricLine,_ time:Float) -> Int {
        //转为毫秒
        let newTime=time*1000
        
        var startTime = Float(line.startTime)
        
        for (index,value) in line.wordDurations!.enumerated() {
            startTime=startTime+Float(value)
            if newTime<startTime{
                let playedTime=Int(Float(value)-(startTime-newTime))
                print("LyricUtil getWordPlayedTime:\(line.data!),\(startTime),\(newTime),\(playedTime)")
                return playedTime
            }
        }
        
        print("LyricUtil getWordPlayedTime:\(line.data!),\(startTime),\(newTime),\(-1)")
        
        return -1
    }
}
